package com.example.myutil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * md5单向加密
 * 
 * @author zxd 2013.08.21
 */
public class EncryptionMD5 {
	private static final Logger LOG = LoggerFactory.getLogger(EncryptionMD5.class);
	public static String eccrypt(String info){
		String res = null;
		// 根据MD5算法生成MessageDigest对象
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] srcBytes = info.getBytes();
			// 使用srcBytes更新摘要
			md5.update(srcBytes);
			// 完成哈希计算，得到result
			byte[] resultBytes = md5.digest();
			res = new String(resultBytes);
		} catch (NoSuchAlgorithmException e) {
			LOG.error("",e);
		}
		
		return res;
	}

	public static String getMD5(String str){
		String result = null;
		byte[] buf = str.getBytes();
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			md5.update(buf);
			byte[] tmp = md5.digest();
			StringBuilder sb = new StringBuilder();
			for (byte b : tmp) {
				int val = (b<0)?(b+256):b;
				if(val < 16) sb.append("0");
				sb.append(Integer.toHexString(val));
			}
			result = sb.toString();
		} catch (NoSuchAlgorithmException e) {
			LOG.error("",e);
		}
		
		return result;
	}
	
	public static String getMD5(String str, String type){
		return sign(str, type);
	}
  //签名     
  public static String sign(String str, String type){
     String s=Encrypt(str,type);
      return s;
  }
  public static String Encrypt(String strSrc, String encName) {
      MessageDigest md = null;
      String strDes = null;
      byte[] bt = strSrc.getBytes();
      try {
          md = MessageDigest.getInstance(encName);
          md.update(bt);
          strDes = bytes2Hex(md.digest()); // to HexString
      } catch (NoSuchAlgorithmException e) {
          System.out.println("签名失败！");
          return null;
      }
      return strDes;
  }
  public static String bytes2Hex(byte[] bts) {
      String des = "";
      String tmp = null;
      for (int i = 0; i < bts.length; i++) {
          tmp = (Integer.toHexString(bts[i] & 0xFF));
          if (tmp.length() == 1) {
              des += "0";
          }
          des += tmp;
      }
      return des;
  }
}
